<?php
namespace app\api\model;

use think\Model;
use app\api\model\Indent;
use think\db;

class Refund extends Model
{

    /**
     * @param $info       数组 [用户id，订单号，退款原因]
     * @param $photo    发起退款的照片
     */
    public function apply($info,$photo)
    {
        $time=date('Ymd',time());
        $filename=time().'image';
        if(!file_exists(ROOT_PATH . 'public' . DS .'static'. DS .'img_refund'))
        {
            mkdir(ROOT_PATH . 'public' . DS .'static'. DS .'img_refund');
        }
        $infos=$photo->move(ROOT_PATH . 'public' . DS .'static'. DS .'img_refund'.DS.$time,$filename);
        $infophoto = $time.DS.$infos->getFileName();
        $starttime = date("Y-m-d H:i:s");
        $indentid = $info['indentid'];
        $userid = $info['id'];
        $cause = $info['cause'];
        //开启事务
        Db::startTrans();
        try {
            $refund = new Refund();
            $query = Db::name('indent')->where(['dnumber'=>$indentid,'userid'=>$userid])->update(['audit'=>1]);
            $query2 = $refund->allowField(true)->save(['indentid'=>$indentid,'cause'=>$cause,'photo'=>$infophoto, 'starttime'=>$starttime]);
            // 判断是否修改成功
            if (!$query || !$query2) {
                throw new \Exception("操作失败");
            }
            // 提交事务
            Db::commit();
            return 1;                  //全部执行成功之后的返回值
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return 0;                //执行失败时的返回值
        }
    }
}